Categories
JavaScript Tips

Useful JavaScript Tips — This, Modules, and Functions

Spread the love

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Returning Objects to Enable Chaining of Functions

We can return objects in methods to let us chain functions.

For instance, we can do that by writing:

const obj = {
  height: 0,
  width: 0,
  setHeight(height) {
    this.height = height;
    return this;
  },
  setWidth(width) {
    this.width = width;
    return this;
  }
}

Then we can call it by running:

obj.setHeight(100).setWidth(300);

and we get that obj.height is 100 and obj.width is 300.

Also, we can do the same for classes.

For instance, we can write:

class Obj {
  setHeight(height) {
    this.height = height;
    return this;
  }

  setWidth(width) {
    this.width = width;
    return this;
  }
}

Then we can write:

new Obj().setHeight(100).setWidth(300)

Safe String Concatenation

We can use the concat method to concatenate strings.

For instance, we can write:

const one = 1;
const two = 2;
const three = '3';
const result = ''.concat(one, two, three);

Then we get that result is '123' .

Run a Module if it’s not Required

We can check the module.parent property to see if a JavaScript file is required by another file.

For instance, we can write:

if (!module.parent) {
  // run code ...
} else {
  module.exports = app;
}

If module.parent is falsy, then we run the code inside the if block.

Otherwise, we export the module members so that they can be required.

Passing Arguments to callback Functions

We can pass arguments to callback function if we create a function that returns the callback with the arguments included.

For instance, we can write:

const callback = (a, b) => {
  return () => {
    console.log(a + b);
  }
}

Then we can write:

const x = 1, y = 2;
document.getElementById('foo').addEventListener('click', callback(x, y));

We called callback to return a function that adds the 2 arguments together.

This means that we can include those arguments in the callback.

Using indexOf to Check if Something is Included

We can use the indexOf method to check if a string has some substring.

For instance, we can write:

'something'.indexOf('thing') !== -1

or:

'something'.indexOf('thing') >= 0

indexOf returns -1 if a substring isn’t found.

If it’s found, then it returns the first index of the substring.

Also, we can use the includes method to do the same thing:

'something'.includes('thing');

Then true is returned if the substring is found.

So, it would return true .

The same methods are also in arrays.

So we can write:

['foo', 'bar'].indexOf('foo') !== -1

or:”

['foo', 'bar'].indexOf('foo') >= 0

or:

['foo', 'bar'].includes('foo')

Arrow Functions

We can use arrow functions to make our code shorter if our function doesn’t have to have its own this .

For instance, we can write:

const squared = arr.map((x) => x ** 2);

We have an implicit return for single statement arrow functions.

It’s much shorter to use them.

However, bind , call , or apply won’t work with them since they don’t have their own this .

Also, we can’t use the arguments object inside it, but that isn’t much of a loss.

Measuring Performance of Our Code

We can use console.time and console.timeEnd to measure the performance of our code.

For instance, we can write:

console.time("populate array");
let arr = Array(100),
    len = arr.length,
    i;

for (i = 0; i < len; i++) {
    arr[i] = new Object();
};
console.timeEnd("populate array");

We start measuring with console.time .

Then we run the code that we want to measure the performance of.

Then we called console.timeEnd to stop measuring.

Making Parameters Mandatory

We can make parameters mandatory if we throw errors in the function that returns the default parameter value.

For instance, we can write:

const err = ( message ) => {
  throw new Error( message );
}

const getSum = (a = err('a is required'), b = err('b is not required')) => a + b

We can call functions when we assign default parameter values.

Therefore, we can throw errors if they’re not set by running the err function.

err only runs if the parameter isn’t set.

Conclusion

We can make chainable functions if we return this in our object or class methods.

Also, we can sure parameters are set if we run a function that throws errors on the right side of the assignment operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *